package com.huika.dealontop.control.base;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.content.Intent;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.android.volley.Request;
import com.android.volley.Response.ErrorListener;
import com.android.volley.VolleyError;
import com.hk.app.android.lib.http.AjaxParams;
import com.hk.app.android.lib.http.VolleyRequestManager;
import com.huika.dealontop.R;
import com.huika.dealontop.support.http.FormResultRequest;
import com.huika.dealontop.support.http.ServerFlagError;
import com.huika.dealontop.utils.UIUtils;
import com.huika.dealontop.views.LoadingDialog;
import com.huika.dealontop.views.ToastMsg;
import com.huika.dealontop.views.common.CommonLoadingView;
import com.huika.dealontop.views.common.CommonNoNetView;
import com.huika.dealontop.views.overlay.OverlayLayout;
import com.huika.huikalib.base.fragment.BaseFragment;

import java.io.UnsupportedEncodingException;
import java.util.HashSet;
import java.util.Set;


public abstract class BaseFra extends BaseFragment implements ErrorListener, OnCancelListener, OnClickListener {
    /**
     * 嵌套viewpager时，第一次显示回调
     *
     * @author fanxing 创建于 Dec 3, 2014
     */
    public interface OnInitShowListener {
        void onInitShow();
    }

    protected View netErrorView;


    /**
     * 分页加载数据，每页数据量
     */
    protected static final int PAGE_SIZE = 8;
    /**
     * 当前页，用于分页加载数据
     */
    protected int CURRENT_PAGE = 1;
    protected int CURRENT_PAGES = 1;
    protected Context context;
    protected LoadingDialog loadingDialog;
    protected OverlayLayout mOverlayLayout;
    private OverlayLayout mEmtyOverlay;
    private View commonEmtyOverlay;
    protected LayoutInflater inflater;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        context = getActivity();
        inflater = LayoutInflater.from(context);
        super.onCreate(savedInstanceState);
    }

    protected void initLoadingDialog(boolean isTrans) {
        if (null == loadingDialog) {
            loadingDialog = new LoadingDialog(getActivity(), isTrans);
            loadingDialog.setOnCancelListener(this);
        }
    }

    public void showLoadingDialog(String parameter) {
        initLoadingDialog(true);//透明
        loadingDialog.setTitle(parameter);
        if (!loadingDialog.isShowing())
            loadingDialog.show();
    }

    /**
     * show to @param(cls)，but can't finish activity
     */
    public void showActivity(Activity aty, Class<?> cls) {
        Intent intent = new Intent();
        intent.setClass(aty, cls);
        aty.startActivity(intent);
        getActivity().overridePendingTransition(R.anim.activity_right_in, R.anim.activity_right_out);
    }

    /**
     * show to @param(cls)，but can't finish activity
     */
    public void showActivity(Activity aty, Intent it) {
        aty.startActivity(it);
        getActivity().overridePendingTransition(R.anim.activity_right_in, R.anim.activity_right_out);
    }

    /**
     * show to @param(cls)，but can't finish activity
     */
    public void showActivity(Activity aty, Class<?> cls, Bundle extras) {
        Intent intent = new Intent();
        intent.putExtras(extras);
        intent.setClass(aty, cls);
        aty.startActivity(intent);
        getActivity().overridePendingTransition(R.anim.activity_right_in, R.anim.activity_right_out);
    }

    @Override
    public void onCancel(DialogInterface dialog) {
    }

    public void dismissLoadingDialog() {
        if (null != loadingDialog) {
            LoadingDialog.dismissDialog(loadingDialog);
        }
    }

    public void showToastMsg(String msg) {
        ToastMsg.showToastMsg(getActivity(), msg);
    }

    public void showToastMsg(int strId) {
        ToastMsg.showToastMsg(getActivity(), strId);
    }

    private Set<Object> tags = new HashSet<Object>();

    /**
     * 添加网络请求
     *
     * @param request
     */
    protected void executeRequest(Request request) {
        VolleyRequestManager.addRequest(request, this);
        tags.add(this);
    }

    /**
     * 添加网络请求
     *
     * @param request
     */
    protected void executeRequest(FormResultRequest request) {
        AjaxParams ajaxParams = request.getRequestParams();
        ajaxParams.putCommonTypeParam("lang", getString(R.string.common_lang));
        VolleyRequestManager.addRequest(request, this);
        tags.add(this);
    }

    /**
     * 取消网络请求
     *
     * @param tag
     */
    protected void cancelRequest(Object tag) {
        VolleyRequestManager.cancelAll(tag);
    }

    @Override
    public void onStop() {
        super.onStop();
        for (Object tag : tags) {
            VolleyRequestManager.cancelAll(tag);
        }
    }

    @Override
    public void startActivity(Intent intent) {
        super.startActivity(intent);
        getActivity().overridePendingTransition(R.anim.activity_right_in, R.anim.activity_right_out);
    }

    @Override
    public void startActivityForResult(Intent intent, int requestCode) {
        super.startActivityForResult(intent, requestCode);
        getActivity().overridePendingTransition(R.anim.activity_right_in, R.anim.activity_right_out);
    }

    //默认网络请求异常回调
    @Override
    public void onErrorResponse(VolleyError error) {
        if (isOvarallLoading) {
            stopOverallLoading();
        } else {
            dismissLoadingDialog();
        }

        String msg = UIUtils.getString(R.string.error_response);
        if (error instanceof ServerFlagError) {
            msg = ((ServerFlagError) error).result.msg;
        } else {
            try {
                if (error.networkResponse != null && error.networkResponse.data != null)
                    msg = new String(error.networkResponse.data, "utf-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }
        showToastMsg(msg);
    }

    /**
     * 要在Fragment中监听按键需要实现该接口
     */
    public interface FragmentKeyDown {
        boolean onFraKeyDown(int keyCode, KeyEvent event);
    }

    private int indexOfContent;
    private ViewGroup parentView;
    private ViewGroup.LayoutParams contentParas;
    private CommonLoadingView commonLoadingView;
    private CommonNoNetView commonNoNetView;
    private ViewGroup contentViewGroup;
    protected boolean isOvarallLoading = false;//是否为全局加载
    protected boolean isNoNetView = false;//是否为全局加载
    protected boolean isEmptyLayView = false;//是否为全局加载

    public void showNoNetView(ViewGroup contentViewGroup, OnClickListener onClickListener) {
        initContentView(contentViewGroup);
        isNoNetView = true;
        if (parentView != null) {
            parentView.removeViewAt(indexOfContent);
            commonNoNetView = (CommonNoNetView) LayoutInflater.from(getActivity()).inflate(R.layout.common_nonet_view,
                    null);
            commonNoNetView.setLayoutParams(contentParas);
            commonNoNetView.setReload(onClickListener);
            commonNoNetView.setCheckNet(getActivity());
            parentView.addView(commonNoNetView, indexOfContent);
        }
    }

    public void hideNoNetView() {
        isNoNetView = false;
        if (parentView != null) {
            parentView.removeViewAt(indexOfContent);
            parentView.addView(contentViewGroup, indexOfContent);
        }
    }

    /**
     * 全局加载
     *
     * @param contentViewGroup
     */
    public void startOverallLoading(ViewGroup contentViewGroup) {
        isOvarallLoading = true;

        initContentView(contentViewGroup);
        if (parentView != null) {
            parentView.removeView(contentViewGroup);
            commonLoadingView = (CommonLoadingView) LayoutInflater.from(getActivity()).inflate(R.layout
                    .common_load_view, null);
            commonLoadingView.setLayoutParams(contentParas);
            commonLoadingView.startLoading();
            parentView.addView(commonLoadingView, indexOfContent);
        }
    }

    public void stopOverallLoading() {
        isOvarallLoading = false;
        if (parentView != null) {
//            commonLoadingView.stopLoading();
            parentView.removeViewAt(indexOfContent);
            contentViewGroup.setLayoutParams(contentParas);
            ViewGroup parent = (ViewGroup) contentViewGroup.getParent();
            if (parent != null) {
                parent.removeView(contentViewGroup);
            }
            parentView.addView(contentViewGroup, indexOfContent);
        }
    }

    private void initContentView(ViewGroup contentViewGroup) {
        this.contentViewGroup = contentViewGroup;
        contentParas = contentViewGroup.getLayoutParams();
        parentView = (ViewGroup) contentViewGroup.getParent();
        if (parentView != null) {
            indexOfContent = parentView.indexOfChild(contentViewGroup);
        }
    }

    /**
     * 覆盖页
     ******************************/
    protected void showOverLay() {
        if (mOverlayLayout != null) {
            mOverlayLayout.showOverlay();
        }
    }

    protected void hideOverLay() {
        if (mOverlayLayout != null) {
            mOverlayLayout.hideOverlay();
        }
    }

    /**
     * 显示数据空页面 : targetView为设置overlay依附的view,resid为提示信息资源id
     */
    TextView empt_tv = null;

    public void showEmptyLayView(View targetView, int resid, int rid) {
        isEmptyLayView = true;
        if (mEmtyOverlay == null) {
            mEmtyOverlay = new OverlayLayout(getActivity());
            commonEmtyOverlay = inflater.inflate(R.layout.search_empty_view,
                    null);
            empt_tv = (TextView) commonEmtyOverlay
                    .findViewById(R.id.tv_emptycontent);
            ImageView empt_iv = (ImageView) commonEmtyOverlay
                    .findViewById(R.id.search_ImageView);
            empt_iv.setBackgroundResource(rid);
            mEmtyOverlay.setOverlayView(commonEmtyOverlay);
            mEmtyOverlay.attachTo(targetView);
        }
        empt_tv.setText(resid);
        mEmtyOverlay.showOverlay();
    }

    /**
     * 影藏数据空页面
     */
    public void hideEmptyLayView() {
        isEmptyLayView = false;
        if (mEmtyOverlay != null)
            mEmtyOverlay.hideOverlay();
    }

    /***
     * 事件监听view的id=R.id.click_reload
     * 显示加载异常
     *
     * @param reloadListener
     */
    protected void setNetErrorClick(View.OnClickListener reloadListener) {
        initNetErrorView();
        if (reloadListener != null) {
            netErrorView.findViewById(R.id.click_reload).setOnClickListener(reloadListener);
            netErrorView.findViewById(R.id.click_checknetwork).setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    // 检查网络设置
                    Intent intent = new Intent();
                    ComponentName component = new ComponentName("com.android.settings", "com.android.settings" +
                            ".Settings");
                    intent.setComponent(component);
                    intent.setAction("android.intent.action.VIEW");
                    getActivity().startActivity(intent);
                }
            });

        }
    }

    protected View initNetErrorView() {
        if (netErrorView == null) {
            initOverlayLayout();
            netErrorView = mOverlayLayout.setOverlayView(R.layout.common_load_error);
        }
        return netErrorView;
    }

    protected void initOverlayLayout() {
        if (mOverlayLayout == null)
            mOverlayLayout = new OverlayLayout(getActivity());
    }


    /**
     * 设置overlay依附的viewgroup
     */
    protected void setOverLayAttachTo(View targetView) {
        initOverlayLayout();
        mOverlayLayout.attachTo(targetView);
    }


    /**
     * 覆盖页 end
     ******************************/

	/* 获取输入内容 */
    public String getInputStr(EditText et) {
        return et.getText().toString().trim();
    }

    /**
     * @param
     * @return void
     * @throws
     * @Description:关闭键盘事件
     * @author: 刘成伟（wwwlllll@126.com）
     * @Title: closeInput
     * @date 2014-4-6 上午11:18:36
     */
    public void closeInput() {
        InputMethodManager inputMethodManager = (InputMethodManager) getActivity().getSystemService(Context
                .INPUT_METHOD_SERVICE);
        if (inputMethodManager != null && getActivity().getCurrentFocus() != null) {
            inputMethodManager.hideSoftInputFromWindow(getActivity().getCurrentFocus().getWindowToken(),
                    InputMethodManager.HIDE_NOT_ALWAYS);
        }
    }

}
